package algo3c3g3.model.action;

import algo3c3g3.model.*;
import org.jdom.Element;

import algo3c3g3.model.persistence.Persistence;

/**
 * La unidad destruye bloques en forma vertical si son destructibles.
 * Si el bloque no es destructible se convierte en Walker.
 */
public class Digger extends Action
{
    private int attemptsFailed;
    
    private static final int MAX_ATTEMPTS_FAILED = 1;
    
    public void perform(Unit unit)
    {
        // Si se supera la cantidad maxima de intentos fallados
        // se vuelve Walker.
        if(attemptsFailed >= MAX_ATTEMPTS_FAILED)
        {
            unit.setAction(new Walker());
            return;
       }
        
        // El piso es rompible. Lo rompe.
        if(unit.floorIsBreakable())
        {
            unit.getOwnerMap().breakBlock(unit.getFloorPosition());
            attemptsFailed = 0;
        }
        // No es rompible (puede ser solido o no)
        else
            attemptsFailed++;
        
        unit.materialEffectY();
        
        if(unit.overSolidFloor() == false)
            unit.fall();
    }
    
    @Override
    public Element save()
    {
        Element root = super.save();

        Element e = new Element("attemptsFailed");
        e.addContent(Integer.toString(this.attemptsFailed));
        root.addContent(e);

        return root;
    }

    @Override
    public void load(Element e)
    {
        this.attemptsFailed =
            new Integer(e.getChildText("attemptsFailed")).intValue();
    }

    
    
    public static void main(String[] args)
    {
        System.out.println();
        
        World world = new World(new Coord(5, 1), null, new TestMaps.TestDiggerMap());
        
        System.out.println("Mapa:");
        world.printMap();
        
        world.addUnit();
        
        Unit unit1 = world.getUnit(0);
        
        System.out.println("\nNueva unidad:");
        unit1.printStatus();
        
        Digger digger=new Digger();
        unit1.setAction(digger);
        
        System.out.println("\nCavando:");
        for(int i = 0; i < 20; i++)
        {
            world.moveUnits();
            unit1.printStatus();
        }
        
        System.out.println();
        
        world.printMap();
        
        Persistence.toXMLFile(digger.save(),"C:\\salida.xml");
    }
}
